package com.itany.book.service.impl;

import com.github.pagehelper.PageInfo;
import com.itany.book.service.UserService;
import com.itany.constant.StatusConstant;
import com.itany.exception.RequestParamException;
import com.itany.exception.UserNotExistException;
import com.itany.mapper.UserMapper;
import com.itany.pojo.User;
import com.itany.utils.ParamUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Auther:ws@itany.com
 * Date:20-10-12 下午3:20
 * Version:1.0
 * Description:
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public PageInfo<User> findUserAll(Integer page, Integer rows, String username, String flag) {
        List<User> users = userMapper.selectUserAll(username, flag);
        PageInfo<User> pageInfo = new PageInfo<>(users);
        return pageInfo;
    }

    @Override
    public User findById(String id) throws RequestParamException, UserNotExistException {
        if (ParamUtils.isNull(id)){
            throw new RequestParamException("请求参数错误");
        }
        User user = userMapper.selectById(Integer.parseInt(id));
        if (null == user){
            throw new UserNotExistException("用户不存在");
        }
        return user;
    }


    @Override
    public void modifyStatus(String id, String Status) throws RequestParamException, UserNotExistException {
        if (ParamUtils.isNull(id)){
            throw new RequestParamException("请求参数错误");
        }

        Integer oldStatus = Integer.parseInt(Status);

        User user = userMapper.selectById(Integer.parseInt(id));
        if (null == user){
            throw new UserNotExistException("用户不存在");
        }
        if (user.getFlag().equals(oldStatus)){
            return;
        }else {
            Integer status = oldStatus.equals(StatusConstant.USER_STATUS_ENABLE) ? StatusConstant.USER_STATUS_ENABLE : StatusConstant.USER_STATUS_DISABLE ;
            user.setFlag(status);
        }
        userMapper.updateUser(user);
    }

    @Override
    public void modifyUser(User user) throws RequestParamException {
        if (ParamUtils.isNull(user.getUsername())){
            throw new RequestParamException("用户名不能为空");
        }
        if (ParamUtils.isNull(user.getPhone())){
            throw new RequestParamException("用户名不能为空");
        }
        if (ParamUtils.isNull(user.getEmail())){
            throw new RequestParamException("用户名不能为空");
        }

        userMapper.updateUser(user);
    }

}
